import type { App, Component, ObjectPlugin } from 'vue'
import { defineAsyncComponent } from 'vue'
// 引入 element-plus 提供全部图标组件
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

type Components = {
  [key: string]: Component
}

const components: Components = {
  SvgIcon: defineAsyncComponent(() => import('@/components/SvgIcon/index.vue')),
  Pagination: defineAsyncComponent(() => import('@/components/Pagination/index.vue')),
}

// 对外暴露插件对象
const globalComponents: ObjectPlugin = {
  // 务必叫做 install 方法
  install: (app: App) => {
    // 注册项目全部的全局组件
    Object.keys(components).forEach((key) => {
      app.component(key, components[key])
    })

    // 讲 element-plus 的图标组件注册到全局
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
      app.component(key, component)
    }
  },
}

export default globalComponents

// 自动注册全局组件
// const components = import.meta.glob('@/component/globel/**/*.vue')

// export default function install(app: App) {
//   for (const [key, value] of Object.entries(components)) {
//     // 提取组件名称, 注意组件文件的命名名称必须和使用组件的名称一致
//     const name = key.substring(key.lastIndexOf('/') + 1, key.lastIndexOf('.'))
//     // 使用类型断言将 value 转换为 () => Promise<Component>
//     app.component(
//       name,
//       defineAsyncComponent(() => value() as Promise<Component>),
//     )
//   }
// }
